﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.Data;

namespace DotNetDal.Core
{
    public class SqlServer
    {
        private static string sqlConnectionString;
        public delegate string NeedConnectionStringHandler(object o, EventArgs e);
        public static event NeedConnectionStringHandler NeedConnectionStringEvent;

        public static SqlConnection GetConnection()
        {
            if (string.IsNullOrEmpty(sqlConnectionString))
            {
                return new SqlConnection(NeedConnectionStringEvent(new object(), new EventArgs()));
            }
            else
                return new SqlConnection(sqlConnectionString);
        }

        public static void RegisterSqlConnectionString(string connString)
        {
            sqlConnectionString = connString;
        }

        public static DataSet GetDataSet(string sql)
        {
            DataSet ds = new DataSet();

            using (SqlConnection conn = GetConnection())
            {
                SqlDataAdapter da = new SqlDataAdapter(sql, conn);
                da.SelectCommand.CommandTimeout = int.MaxValue;

                try
                {
                    da.Fill(ds);
                }
                catch (System.Exception ex)
                {
                    string a = ex.Message;
                }
            }

            return ds;
        }

        public static SqlDataReader GetDataReader(string sql, SqlParameter[] sqlParams)
        {
            SqlConnection conn = GetConnection();

            conn.Open();

            SqlCommand command = new SqlCommand(sql, conn);

            command.Parameters.AddRange(sqlParams);
            command.CommandTimeout = int.MaxValue;

            return command.ExecuteReader(CommandBehavior.CloseConnection);
        }

        public static void ExecuteNonQuery(string sql, SqlParameter[] sqlParams)
        {
            using (SqlConnection conn = GetConnection())
            {
                conn.Open();

                try
                {
                    SqlCommand cmd = new SqlCommand(sql, conn);
                    cmd.Parameters.AddRange(sqlParams);
                    cmd.CommandTimeout = int.MaxValue;
                    cmd.ExecuteNonQuery();
                }
                finally
                {
                    conn.Close();
                }
            }
        }

        public static DbType FromSqlDbType(SqlDbType sdt)
        {
            SqlParameter sp = new SqlParameter();

            sp.SqlDbType = sdt;

            return sp.DbType;
        }
    }
}
